package com.small.nacos.naming.healthcheck;

import com.small.nacos.naming.core.Instance;
import com.small.nacos.naming.core.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @Author zhoujin
 * @Date 2022/10/15 17:55
 */
public class ClientBeatProcessor implements Runnable {

    private RsInfo rsInfo;

    private Service service;

    public ClientBeatProcessor(RsInfo rsInfo, Service service) {
        this.rsInfo = rsInfo;
        this.service = service;
    }

    @Override
    public void run() {
        String ip = rsInfo.getIp();
        String clusterName = rsInfo.getCluster();
        int port = rsInfo.getPort();
        Boolean ephemeral = rsInfo.isEphemeral();
        List<Instance> instances = service.allIPs(Arrays.asList(clusterName), ephemeral);
        for (Instance instance : instances) {
            if (instance.getIp().equals(ip) && instance.getPort() == port) {
                instance.setLastBeat(System.currentTimeMillis());
                if (!instance.isHealthy()) {
                    instance.setHealthy(true);
                }
            }
        }
    }
}
